<?php

namespace App\Admin\Controllers\education;

use App\Admin\Renderable\AdminGroupTable;
use App\Admin\Renderable\SchoolTable;
use App\Admin\Renderable\UserTable;
use App\Admin\Repositories\AdminSchool;
use App\Models\AdminEducation;
use App\Models\AdminManager;
use App\Models\AdminManagerType;
use App\Models\AdminUserGroup;
use App\Models\User;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Form\NestedForm;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request;

class CreateController extends AdminController
{
    protected $title = "项目";

    protected $translation = 'admin-education';

    public function index(Content $content)
    {
        return $content
            ->translation($this->translation())
            ->title($this->title())
            ->description($this->description()['create'] ?? trans('admin.create'))
            ->body($this->form());
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new AdminManager(), function (Form $form) {
            $form->disableListButton();
            $form->action('/education/step');
            $form->multipleSteps()
                ->remember()
                ->add('基本信息',fn($step) => $this -> firstFrom($step) )
                ->add('选填信息',fn($step) => $this -> secondFrom($step))
                ->add('助学详情', fn($step) => $this -> thirdFrom($step));
        });
    }

    public function firstFrom($form) {
        $form->text('title')
            ->required();

        $form->textarea('description')
            ->required();

        $form->radio('educational_type')
            ->options(function () {
                return trans('admin-education.options.educational_type');
            })
            ->default(0)
            ->required();

        $map_data = [
            'name'      => 'address',
            'address'   => $form->model()->address,
            'longitude' => $form->model()->longitude,
            'latitude'  => $form->model()->latitude
        ];

        $form->html(view('admin.components.map-dialog', $map_data)->render(),'助学地址')
            ->required();

        $form->number('target_amount')
            ->required();

        $form->selectTable('user_id')
            ->from(UserTable::make(['id' => $form->getKey()]))
            ->model(User::class, 'id', 'name')
            ->required();

        $form->selectTable('group_id')
            ->from(AdminGroupTable::make(['id' => $form->getKey()]))
            ->model(AdminUserGroup::class, 'id', 'name')
            ->required();

        $form->image('cover_path')
            ->url('/upload')
            ->uniqueName()
            ->autoUpload()
            ->maxSize(5120)
            ->required();
    }
    public function secondFrom($form)
    {
        $student_info = [
            'title' => '学生',
            'left_name' => 'student_name',
            'left_value' => '',
            'right_name' => 'student_phone',
            'right_value' => ''
        ];
        $form->html(view('admin.components.step-column', $student_info)->render(), '学生信息');
        $head_teacher_info = [
            'title' => '班主任',
            'left_name' => 'head_teacher',
            'left_value' => '',
            'right_name' => 'head_teacher_phone',
            'right_value' => '',
        ];
        $form->html(view('admin.components.step-column', $head_teacher_info)->render(), '班主任信息');
        $guardian_info = [
            'title' => '监护人',
            'left_name' => 'guardian_name',
            'left_value' => '',
            'right_name' => 'guardian_phone',
            'right_value' => '',
        ];
        $form->html(view('admin.components.step-column', $guardian_info)->render(), '监护人信息');
        $form->radio('student_sex')->options(trans('global.options.sex'));
        $form->text('student_address');
        $form->text('class_name');
        $form->date('student_birthday');
        $form->selectTable('school_id')
            ->from(SchoolTable::make())
            ->model(AdminSchool::class, 'id', 'school_name');
        $form->date('enrollment_year');
        $form->text('source');
        $form->text('guardian_relation');
        $form->text('payment_info');
    }
    public function thirdFrom($form)
    {
        $form->editor('content')->required();
    }
    public function validateStepForm(Request $request)
    {
        $step = $request->input('CURRENT_VALIDATION_STEP');

        $all = $request->input('ALL_STEPS', 0);

        if($all == 1) {
            return $this->finishStepForm($request);
        }

        switch($step) {
            case 0:
                return $this -> validateFirstStepFrom($request);
            case 1:
                return $this -> validateSecondStepFrom($request);
            case 2:
                return $this -> validateThirdStepFrom($request);
        }
    }
    public function finishStepForm(Request $request)
    {
        $model = new AdminEducation();

        $data = $request->only($model->getFillable());

        $data['admin_id'] =  Admin::user()->id;

        $model->create($data);

        $data = [
            'title'       => trans('admin.save_succeeded'),
            'description' => '',
            'createUrl'   => '/admin/education/create',
            'backUrl'     => '/admin/education/list',
        ];

        return view('dcat-admin.form-step::completion-page', $data);
    }
    public function validateFirstStepFrom(Request $request)
    {
        return $request->validate([
            'title'                          => 'required|string|max:100',
            'description'                    => 'required|string|max:200',
            'educational_type'               => 'required|in:0,1',
            'address'                        => 'required|string',
            'longitude'                      => 'required|numeric|between:-180,180',
            'latitude'                       => 'required|numeric|between:-90,90',
            'target_amount'                  => 'required|numeric|min:0',
            'user_id'                        => 'required|exists:users,id',
            'group_id'                       => 'required|exists:admin_user_groups,id',
            'cover_path'                     => 'required',
        ], [
            'title.required'                          => '请输入助学标题',
            'description.required'                    => '请输入助学简介',
            'educational_type.required'               => '请选择助学类型',
            'address.required'                        => '请选择助学项目地址',
            'longitude.required'                      => '请输入经度',
            'longitude.between'                       => '经度必须在-180到180之间',
            'latitude.required'                        => '请输入纬度',
            'latitude.between'                        => '纬度必须在-90到90之间',
            'target_amount.required'                  => '请输入助学目标金额',
            'target_amount.min'                       => '目标金额不能为负数',
            'user_id.required'                        => '请选择项目负责人',
            'user_id.exists'                          => '项目负责人不存在',
            'group_id.required'                       => '请选择项目所属团队',
            'group_id.exists'                         => '团队不存在',
            'cover_path.required'                     => '请上传封面图片',
        ]);
    }
    public function validateSecondStepFrom(Request $request)
    {

        return $request->validate([
            'student_name'       => 'nullable|max:100',
            'student_phone'      => 'nullable|max:12',
            'head_teacher'       => 'nullable|max:100',
            'head_teacher_phone' => 'nullable|max:12',
            'guardian_name'      => 'nullable|max:100',
            'guardian_phone'     => 'nullable|max:12',
            'class_name'         => 'nullable|max:100',
            'student_sex'        => 'nullable|in:0,1',
            'student_birthday'   => 'nullable|date',
            'school_id'          => 'nullable|exists:admin_school,id',
            'enrollment_year'    => 'nullable|date',
            'source'             => 'nullable|max:100',
            'guardian_relation'  => 'nullable|max:32',
            'payment_info'       => 'nullable|max:100',
            'student_address'    => 'nullable|max:100',
        ], [
            'student_name.max'       => '学生名称格式错误',
            'student_phone.max'      => '学生电话格式错误',
            'head_teacher.max'       => '班主任名称格式错误',
            'head_teacher_phone.max' => '班主任电话格式错误',
            'guardian_name.max'      => '监护人名称格式错误',
            'guardian_phone.max'     => '监护人电话格式错误',
            'class_name.max'         => '班级格式错误',
            'student_birthday.date'  => '学生生日格式错误',
            'school_id.exists'       => '学校不存在',
            'enrollment_year.exists' => '入学年份格式错误',
            'source.max'             => '来源格式错误',
            'guardian_relation.max'  => '监护人关系格式错误',
            'payment_info.max'       => '收款账户格式错误',
            'student_address.max'    => '学生地址格式错误',
        ]);
    }
    public function validateThirdStepFrom(Request $request)
    {

        return $request->validate([
            'content'     => 'required'
        ], [
            'content.required'   => '请填写具体内容',
        ]);
    }
}

